﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ZT.Core.IService;
using ZT.Core.MiddleWare;

namespace ZT.Core.API.Controllers
{
    /// <summary>
    /// 微信公众号
    /// </summary>
    [Route("api/wx")]
    [ApiController]
    public class WeChatController : BaseController
    {

        private IWechat bll = null;
        public WeChatController(IWechat wechat)
        {
            bll = wechat;
            Services.Add(wechat);
        }
        /// <summary>
        /// 静默获取openid鉴权
        /// </summary>
        [HttpGet]
        [AllowAnymous]
        [Route("authCode")]
        public void GetCode(string url)
        {
            HttpContext context = HttpContext.Request.HttpContext;
            context.Response.ContentType = "text/plain";
            string BusinessUrl = url;// context.Request.Query["url"].FirstOrDefault(); //业务页面地址
            string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WxHelper.WxConfig.Config.AppID + "&redirect_uri=" + WxHelper.WxConfig.Config.Openid_redirecturl + "&response_type=code&scope=snsapi_base&state=" + BusinessUrl + "#wechat_redirect";

            context.Response.Redirect(codeurl);
        }

        /// <summary>
        /// 创建微信菜单
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("createMenu")]
        public WxHelper.Dto.WxResult<string> CreateMenu(WxHelper.Dto.WxMenu menu)
        {
           
            return WxHelper.WxService.CreateMenu(menu);
        }
        /// <summary>
        /// 获取微信菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("getMenu")]
        public WxHelper.Dto.WxResult<WxHelper.Dto.WxMenuQuery> GetMenu()
        {
            return WxHelper.WxService.GetMenu();
        }

        /// <summary>
        /// 获取openid
        /// </summary>
        [HttpGet]
        [AllowAnymous]
        [Route("authOpenId")]
        public void GetOpenID()
        {
            HttpContext context = HttpContext;
            context.Response.ContentType = "text/plain";

            string code = context.Request.Query["code"];
            string state = context.Request.Query["state"];
            //获取openid
            string resultJosn = WxHelper.WxAction.WxAPIGet(WxHelper.WxConfig.WxActionType.GetOpenID, "", code);
            string openid = "";
            JObject jo = JObject.Parse(resultJosn);
            if (!resultJosn.Contains("errcode"))
            {
                openid = jo["openid"].ToString();
                if (state.Contains("%3F") || state.Contains("?"))//如果返回页面带参数
                {

                    context.Response.Redirect(state + "&openID=" + openid);
                }
                else
                {

                    context.Response.Redirect(state + "?openID=" + openid);
                }
            }
            else
            {
                string errmsg = jo["errmsg"].ToString();
                context.Response.Redirect(state + "?errmsg=" + errmsg);
            }
        }
        /// <summary>
        /// 用于接收并回复微信服务器的信息
        /// </summary>
        /// <returns></returns>
        [AllowAnymous]
        [HttpGet]
        [HttpPost]
        [Route("getMsg")]
        public async Task GetMessageAsync()
        {
            HttpContext context = HttpContext;
            context.Response.ContentType = "text/plain";
            string HttpMethod = context.Request.Method.ToUpper();
            string responseXML = string.Empty;
            XElement requestXML;
            switch (HttpMethod)
            {
                case "GET":
                    string signature = context.Request.Query["signature"]; //微信加密签名
                    string timestamp = context.Request.Query["timestamp"];// 时间戳
                    string nonce = context.Request.Query["nonce"]; //   随机数
                    string echostr = context.Request.Query["echostr"]; //随机字符串
                    if (!string.IsNullOrEmpty(signature) || !string.IsNullOrEmpty(timestamp) || !string.IsNullOrEmpty(nonce) || !string.IsNullOrEmpty(echostr))
                    {

                        //检查加密签名是否正确
                        if (WxHelper.WxMsgHelper.CheckSignaTrue(signature, timestamp, nonce))
                        {
                            responseXML = echostr;
                         
                        }
                        else
                        {
                          
                        }

                    }
                    else
                    {
                        
                    }
                    break;
                case "POST":
                   
                    // 解析微信请求
                    requestXML = XElement.Load(context.Request.Body);
                    var msg = $"接受信息：{requestXML}\r\n";
                    try
                    {
                        responseXML = bll.WxResInfo(requestXML);
                        //获取地理位署
                        //await _wechatservice.ReceiveMsg(requestXML);
                        //Task.Run(async () => {

                        //});
                        msg += $"回复信息：{responseXML}";

                    }
                    catch (Exception ex)
                    {
                        var result = ex;
                        msg += $"错误信息：{ex.Message}";
                    }
                   // LogContent = msg;
                    break;
            }
            await context.Response.WriteAsync(responseXML);

        }

    }
}